package jobx

import (
	"github.com/prometheus/client_golang/prometheus"
	"github.com/robfig/cron/v3"
	"go.uber.org/zap"
	"jk-time/webook/internal/web/job"
	"strconv"
	"time"
)

type CronJobBuilder struct {
	p *prometheus.SummaryVec
}

func NewCronJobBuilder(Namespace, Subsystem, Name, Help string) *CronJobBuilder {
	p := prometheus.NewSummaryVec(prometheus.SummaryOpts{
		Namespace: Namespace,
		Subsystem: Subsystem,
		Name:      Name,
		Help:      Help,
	}, []string{"name", "success"})
	prometheus.MustRegister(p)
	return &CronJobBuilder{p: p}
}

func (b *CronJobBuilder) Build(job job.Job) cron.Job {
	name := job.Name()

	return cronJobFuncAdapter(func() error {
		var err error
		startTime := time.Now()
		zap.L().Debug("任务开始 ", zap.String("job", name))
		defer func() {
			dura := time.Since(startTime).Milliseconds()
			b.p.WithLabelValues(name, strconv.FormatBool(err == nil)).Observe(float64(dura))
			zap.L().Debug("任务结束 ", zap.String("job", name))
		}()
		err = job.Run()
		if err != nil {
			zap.L().Error("job运行失败 ", zap.Error(err))
		}
		return nil
	})
}

type cronJobFuncAdapter func() error

func (c cronJobFuncAdapter) Run() {
	c()
}
